package com.kevin;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.jvnet.substance.skin.SubstanceGreenMagicLookAndFeel;

import com.kevin.model.db.DBTableModel;
import com.kevin.service.DBTabelService;
import com.kevin.swing.MenuBar;
import com.kevin.swing.TrayIconKevin;
import com.kevin.swing.impl.ContentStep1JPanel;
import com.kevin.swing.impl.ContentStep2JPanel;
import com.kevin.swing.impl.ContentStep3JPanel;
import com.kevin.util.CacheUtil;
import com.kevin.util.log.StdOutErrRedirect;

import lombok.extern.log4j.Log4j;

@Log4j
public class MainFrame extends JFrame {

    private static final long serialVersionUID = -1534907012085790087L;
    private List<String> selectedTables = new ArrayList<>(); // 选中的表名
    private List<DBTableModel> searchTables = new ArrayList<>(); // 搜索处理的表
    public static final String VERSION = "1.0"; // 版本号
    // 菜单栏
    private MenuBar mainBar;
    // 第一步JPanel
    private ContentStep1JPanel contentStep1Panel;
    // 第二步JPanel
    private ContentStep2JPanel contentStep2Panel;
    // 第三步JPanel
    private ContentStep3JPanel contentStep3Panel;
    // 数据库服务
    private DBTabelService dbTableService;

    // 底部
    private JPanel displayPanel;
    private JPanel btnPanel; // 按钮
    private JButton preBtn;
    private JButton nextBtn;

    private int step = 0;

    private SystemTray systemTray; // 系统托盘
    private TrayIconKevin trayIcon = null;
    private Image img;// 图标

    public MainFrame() {
        super("主程序");
        try {
            StdOutErrRedirect.redirectSystemOutAndErrToLog(); // 控制台日志重定向

            log.warn("缓存文件路径：：" + CacheUtil.getCachePath());
            mainBar = new MenuBar(this);
            setJMenuBar(mainBar); //
            setPanel();
            initFrame(650, 450);
            loadDBTableService();
        } catch (Exception e) {
            log.error("异常", e);
            showError(e.getMessage());
            System.exit(0); // 退出
        } catch (Throwable e) {
            log.error("错误", e);
            System.exit(0); // 退出
        }
    }

    /**
     * 加载DB服务类
     * 
     * @Title loadDBTableService
     * @author 吕凯
     * @date 2016年8月25日 下午5:33:27 void
     */
    public void loadDBTableService() {
        dbTableService = DBTabelService.getInstance();
    }

    private void initFrame(int frameWidth, int frameHeight) {
        URL url = this.getClass().getResource("/images/picasa.png");
        img = Toolkit.getDefaultToolkit().getImage(url);
        setIconImage(img);
        addSystemTray(); // 增加系统托盘
        setTitle("数据库表生成实体类");
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension screenDimension = tk.getScreenSize();
        int screenWidth = screenDimension.width;
        int screenHeight = screenDimension.height;
        setLocation((screenWidth - frameWidth) / 2, (screenHeight - frameHeight) / 2);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setSize(frameWidth, frameHeight);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                exitSoft();
            }
        });

        addWindowStateListener(state -> {
            if (state.getNewState() == 1 || state.getNewState() == 7) {
                log.info("窗口最小化");
                showTray();
            } else if (state.getNewState() == 0) {
                log.info("窗口恢复到初始状态");
            } else if (state.getNewState() == 6) {
                log.info("窗口最大化");
            } else {
                log.info(state.getNewState());
            }

        });
    }

    /**
     * 显示系统托盘
     * 
     * @Title showTray
     * @author 吕凯
     * @date 2016年8月27日 下午3:51:08 void
     */
    private void showTray() {
        try {
            if (SystemTray.isSupported()) {// 判断系统是否支持系统托盘
                if (trayIcon != null) {
                    systemTray.remove(trayIcon);
                    systemTray.add(trayIcon);
                }
            }
        } catch (Exception e1) {
            log.error("", e1);
        }
    }

    /**
     * 增加系统托盘
     * 
     * @Title addSystemTray
     * @author 吕凯
     * @date 2016年8月27日 下午3:51:20 void
     */
    private void addSystemTray() {
        // 获取默认的图片
        if (SystemTray.isSupported()) {// 判断系统是否支持系统托盘
            if (systemTray == null) {
                systemTray = SystemTray.getSystemTray();// 创建系统托盘
                if (trayIcon != null) {
                    systemTray.remove(trayIcon);
                }
            }
        }
        // 创建弹出式菜单
        JPopupMenu popup = new JPopupMenu();
        // 主界面选项
        JMenuItem mainMenuItem = new JMenuItem("主界面");
//              mainMenuItem.setActionCommand("main menu");  
        mainMenuItem.addActionListener(e -> {
            showMainFrame();
        });
        // 退出程序选项
        JMenuItem exitMenuItem = new JMenuItem("退出");
        exitMenuItem.addActionListener(e -> {
            exitSoft();
        });

        popup.add(mainMenuItem);
        // 弹出式菜单添加分割线
        popup.addSeparator();
        popup.add(exitMenuItem);

        trayIcon = new TrayIconKevin(img);// 创建trayIcon
        trayIcon.setJPopupMenu(popup);
        trayIcon.setImageAutoSize(true);
        trayIcon.addActionListener(e -> {
            showMainFrame();
        });
    }

    /**
     * 显示主窗口
     * 
     * @Title showMainFrame
     * @author 吕凯
     * @date 2016年8月27日 下午3:57:18 void
     */
    private void showMainFrame() {
        MainFrame.this.setVisible(true);
        MainFrame.this.setExtendedState(JFrame.NORMAL); // 还原窗口
        MainFrame.this.toFront();
        systemTray.remove(trayIcon);
    }

    /**
     * 退出操作
     * 
     * @Title exitSoft
     * @author 吕凯
     * @date 2016年8月25日 下午2:12:17 void
     */
    public void exitSoft() {
        int i = JOptionPane.showConfirmDialog(null, "确定要退出程序吗？", "退出程序", JOptionPane.YES_NO_OPTION);
        if (i == JOptionPane.YES_OPTION) {
            this.dispose();
            CacheUtil.shutdown();
            System.exit(0);
        }
    }

    public static void showError(String msg) {
        JOptionPane.showMessageDialog(null, "运行出错：" + msg + ";具体内容可查看log日志！", "错误", JOptionPane.YES_NO_OPTION);
    }

    private void setPanel() throws Exception {
        contentStep1Panel = new ContentStep1JPanel(this);

        displayPanel = new JPanel();
        btnPanel = new JPanel();
        displayPanel.setLayout(new BorderLayout());
        addStepPanel();// 上一步、下一步

        add(displayPanel, BorderLayout.SOUTH);
        add(contentStep1Panel, BorderLayout.CENTER);
        add(displayPanel, BorderLayout.SOUTH);
    }

    /**
     * 添加上一步、下一步Panel
     * 
     * @Title addStepPanel
     * @author 吕凯
     * @date 2016年8月23日 下午3:20:18 void
     */
    private void addStepPanel() {
        displayPanel.add(btnPanel, BorderLayout.SOUTH);

//        dispalyBtn = new JButton("123");
//        dispalyBtn.setHorizontalTextPosition(JLabel.RIGHT);
//        dispalyBtn.setText("显示10条");
//        dispalyBtn.setIcon(new ImageIcon(SysProperty.class.getResource("/").getPath() + "images/zip.png"));
//        dispalyBtn.setIconTextGap(JLabel.EAST);
//        btnPanel.add(dispalyBtn);
        preBtn = new JButton("上一步");
        nextBtn = new JButton("下一步");
        btnPanel.add(preBtn);
        btnPanel.add(nextBtn);
        preBtn.setEnabled(false);
        nextBtn.setEnabled(false);
        // 下一步
        nextBtn.addActionListener(e -> {
            step++;
            jsPaneStep();

        });
        // 上一步
        preBtn.addActionListener(e -> {
            step--;
            jsPaneStep();

        });
    }

    private void jsPaneStep() {
        if (step == 1) {
            if (selectedTables.size() == 0) {// 未选择表
                JOptionPane.showMessageDialog(this, "未选择表，不能进行下一步！");
                disenabledNextStep();
                step--;
                return;
            }
            if (contentStep2Panel == null) {
                contentStep2Panel = new ContentStep2JPanel(this);
            }
            contentStep2Panel.fillData();
            contentStep2Panel.setVisible(true);
            contentStep1Panel.setVisible(false);
            if (contentStep3Panel != null) {
                contentStep3Panel.setVisible(false);
            }
            add(contentStep2Panel, BorderLayout.CENTER);
            preBtn.setEnabled(true);
            nextBtn.setEnabled(true);
        } else if (step == 2) {
            if (contentStep3Panel == null) {
                contentStep3Panel = new ContentStep3JPanel(this);
            }
            contentStep3Panel.fillData();
            contentStep3Panel.setVisible(true);
            contentStep2Panel.setVisible(false);
            contentStep1Panel.setVisible(false);
            add(contentStep3Panel, BorderLayout.CENTER);
            nextBtn.setEnabled(false);
            preBtn.setEnabled(true);
        } else if (step == 0) { // 第一步
            contentStep1Panel.setVisible(true);
            contentStep2Panel.setVisible(false);
            contentStep3Panel.setVisible(false);
            add(contentStep1Panel, BorderLayout.CENTER);
            preBtn.setEnabled(false);
            nextBtn.setEnabled(true);
        }
    }

    /**
     * 
     * 显示步骤
     * 
     * @Title showStep
     * @author 吕凯
     * @date 2016年8月24日 上午9:08:26 void
     */
    public void showStep1() {
        btnPanel.setVisible(true);
    }

    /**
     * 下一步设为可用
     * 
     * @Title showNextStep
     * @author 吕凯
     * @date 2016年8月26日 上午8:17:03 void
     */
    public void enabledNextStep() {
        nextBtn.setEnabled(true);
    }

    /**
     * 隐藏步骤
     * 
     * @Title hideStep
     * @author 吕凯
     * @date 2016年8月24日 上午9:08:37 void
     */
    public void hideStep1() {
        btnPanel.setVisible(false);
    }

    public void disenabledNextStep() {
        nextBtn.setEnabled(false);
    }

    public List<String> getSelectedTables() {
        if (selectedTables == null) {
            selectedTables = new ArrayList<String>();
        }
        return selectedTables;
    }

    public void setSelectedTables(List<String> selectedTables) {
        this.selectedTables = selectedTables;
    }

    public void addSelectedTables(String tableName) {
        selectedTables.add(tableName);
    }

    public List<DBTableModel> getSearchTables() {
        return searchTables;
    }

    public void setSearchTables(List<DBTableModel> searchTables) {
        this.searchTables = searchTables;
    }

    public DBTabelService getDbTableService() {
        return dbTableService;
    }

    public void setDbTableService(DBTabelService dbTableService) {
        this.dbTableService = dbTableService;
    }

    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        log.info(UIManager.getSystemLookAndFeelClassName());
        try {
//            SwingUtilities.invokeLater(new Runnable() {// 5.3及以后 多jar包trident.jar
//                        @Override
//                        public void run() {
//
//                            try {
//                                SubstanceLookAndFeel.setSkin(new GreenMagicSkin());
//                            } catch (Exception e) {
//                                // e.printStackTrace();
//                            }
//                        }
//
//                    });

//            Class.forName("org.jvnet.substance.SubstanceLookAndFeel");
//            UIManager.LookAndFeelInfo substance = new UIManager.LookAndFeelInfo("Substance", "org.jvnet.substance.SubstanceLookAndFeel");
//            UIManager.installLookAndFeel(substance);
//            UIManager.LookAndFeelInfo[] AVAILABLES = UIManager.getInstalledLookAndFeels();
//            for (UIManager.LookAndFeelInfo available : AVAILABLES) {
//                System.out.println(available.getName());
//            }
            UIManager.setLookAndFeel(new SubstanceGreenMagicLookAndFeel());// 旧版去除两jar包
        } catch (Exception e) {
            log.error("Substance Raven Graphite failed to initialize");
        }
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MainFrame w = new MainFrame();
                w.setVisible(true);
            }
        });
    }
}
